package com.lixw.jdbc.core.transaction;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 简化的事务管理器，支持 REQUIRED 模式
 */
public class SimpleTransactionManager {

    // 存储当前线程的连接和事务状态
    private static final ThreadLocal<Connection> connectionHolder = new ThreadLocal<>();
    private static final ThreadLocal<AtomicBoolean> transactionActive = new ThreadLocal<>();

    // 数据源
    private static final DataSource dataSource;


    static {
        Properties properties = new Properties();
        try {
            properties.load(SimpleTransactionManager.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 开启事务（REQUIRED 模式）
     */
    public static void begin() throws SQLException {
        if (isInTransaction()) {
            return; // 如果已有事务，直接加入
        }

        Connection conn = dataSource.getConnection();
        conn.setAutoCommit(false);
        connectionHolder.set(conn);
        transactionActive.set(new AtomicBoolean(true));
    }

    /**
     * 提交事务
     */
    public static void commit() throws SQLException {
        if (!isInTransaction()) {
            throw new IllegalStateException("No active transaction to commit");
        }

        Connection conn = connectionHolder.get();
        try {
            conn.commit();
        } finally {
            releaseResources();
        }
    }

    /**
     * 回滚事务
     */
    public static void rollback() throws SQLException {
        if (!isInTransaction()) {
            throw new IllegalStateException("No active transaction to rollback");
        }

        Connection conn = connectionHolder.get();
        try {
            conn.rollback();
        } finally {
            releaseResources();
        }
    }

    /**
     * 获取当前线程的连接（用于 DAO 操作）
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = connectionHolder.get();
        if (conn == null) {
            conn = dataSource.getConnection(); // 如果没有事务，直接获取新连接
            connectionHolder.set(conn);
        }
        return conn;
    }

    /**
     * 判断当前线程是否处于事务中
     */
    private static boolean isInTransaction() {
        return transactionActive.get() != null && transactionActive.get().get();
    }

    /**
     * 释放连接和标记事务结束
     */
    public static void releaseResources() throws SQLException {
        Connection conn = connectionHolder.get();
        if (conn != null) {
            conn.setAutoCommit(true); // 恢复自动提交
            conn.close();
        }
        connectionHolder.remove();
        transactionActive.remove();
    }
}